We are now crossing into a new plateau when it comes to programming. The last few posts were to lay the foundation of what out-of-the-box data types Python has and how you can work with them. We barely scratched what you can do with each Python data type. The previous posts just gave you an idea of what to do with each data type. The most important thing in your tool belt would be to bookmark the Python Documentation page, specifically the library reference. I have been and will be using Python 3.8 in these blog posts. You can find the library reference for Python 3.8.
The next few posts will focus on controlling the flow with your Python script/program. We are going to look at the following:
- Conditional Logic
- If / Elif / Else
- For Loops
- While Loops
It may seem daunting to figure out which one to use and when to use it as a new Python programmer. I had this same problem, and I will walk you through my logic in approaching which one to use.
Before we talk about statements, we need to talk about comparison operators. These are vital in how we want our scripts/programs to “flow.” Python comparison operators are:
Comparison Operators
Syntax | Description | Example |
---|---|---|
> | Greater than | 5 > 4 |
< | Less than | 6 < 12 |
<= | Less than or equal to | 6 <= 6 |
>= | Greater than or equal to | 50 >= 50.0 |
== | Equal to | 5 == 5 |
!= | Not equal to | 50 != 100 |
Comparison operators can be used on any data type you want to compare. Items that are compared have to be the same data type, for example:
'a' > 'b'
'cat' == 'cat'
[] == []
[1,2,3] < [4,5,6]
1 < 2 > 3.0
50 > 23 > 100
'a' > 'A'
When we run 'a' > 'A'
. Lowercase ‘a’ greater than the capital ‘A”. This has to do with the ordinal value that we can find if we pass the string into the ord()
method
print(ord('a'))
97
print(ord('A'))
65